package com.cskaoyan.utils;

import com.cskaoyan.Main;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 创建日期: 2022/07/05 16:09
 *
 * @author ciggar
 */
public class DBCPUtils {

    static DataSource dataSource;

    static {

        try {
            Properties properties = new Properties();
            // 这种方式现在使用，没有问题，但是在项目被打包成jar或者war文件了之后，就会存在找不到配置文件的情况
            // properties.load(new FileInputStream("src/main/resources/dbcp.properties"));

            // 建议使用类加载器来找配置文件
            ClassLoader classLoader = DBCPUtils.class.getClassLoader();
            // ClassLoader classLoader1 = Main.class.getClassLoader();

            InputStream in = classLoader.getResourceAsStream("dbcp.properties");

            URL url = classLoader.getResource("dbcp.properties");
            String path = url.getPath();
            System.out.println("path:" + path);
            FileInputStream fileInputStream = new FileInputStream(path);


            properties.load(in);


            dataSource = BasicDataSourceFactory.createDataSource(properties);

        }catch (Exception ex) {
            System.out.println("创建数据库连接池失败！");
            ex.printStackTrace();
        }
    }

    // 获取连接的方法
    public static Connection getConnection() throws SQLException {

        return dataSource.getConnection();


    }



}
